package com.espressif.iot.command.device.New;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.espressif.iot.base.api.EspBaseApiUtil;
import com.espressif.iot.base.application.EspApplication;
import com.espressif.iot.device.IEspDevice;
import com.espressif.iot.device.builder.BEspDevice;
import com.espressif.iot.model.device.EspDeviceGateway;
import com.espressif.iot.type.device.EspDeviceType;
import com.espressif.iot.type.device.state.EspDeviceState;
import com.espressif.iot.type.net.HeaderPair;
import com.espressif.iot.type.net.IOTAddress;
import com.espressif.iot.util.BSSIDUtil;
import com.espressif.iot.util.TimeUtil;
import com.mob.tools.utils.HEX;

public class EspCommandDeviceNewActivateLocal implements IEspCommandDeviceNewActiveLocal
{
    private final static Logger log = Logger.getLogger(EspCommandDeviceNewActivateLocal.class);
    
    private static final long ONLINE_TIMEOUT_PLUG = 60 * TimeUtil.ONE_SECOND_LONG_VALUE;
    
    private static final long ONLINE_TIMEOUT_LIGHT = 60 * TimeUtil.ONE_SECOND_LONG_VALUE;
    
    private static final long ONLINE_TIMEOUT_TEMPERATURE = 5 * TimeUtil.ONE_MINUTE_LONG_VALUE;
    
    private static final long ONLINE_TIMEOUT_GAS_SIREN = 5 * TimeUtil.ONE_MINUTE_LONG_VALUE;
    
    private static final long ONLINE_TIMEOUT_REMOTE = 60 * TimeUtil.ONE_SECOND_LONG_VALUE;
    
    private static final long ONLINE_TIMEOUT_PLUGS = 60 * TimeUtil.ONE_SECOND_LONG_VALUE;
    
    private static final long ONLINE_TIMEOUT_VOLTAGE = 60 * TimeUtil.ONE_SECOND_LONG_VALUE;
  
    private static final long ONLINE_TIMEOUT_GATEWAY = 60 * TimeUtil.ONE_SECOND_LONG_VALUE;
    
    private boolean isDeviceOnline(EspDeviceType deviceType, long last_active, long currentTime)
    {
        long timeout = 0;
        switch (deviceType)
        {
            case FLAMMABLE:
                timeout = ONLINE_TIMEOUT_GAS_SIREN;
                break;
            case HUMITURE:
                timeout = ONLINE_TIMEOUT_TEMPERATURE;
                break;
            case LIGHT:
                timeout = ONLINE_TIMEOUT_LIGHT;
                break;
            case VOLTAGE:
                timeout = ONLINE_TIMEOUT_VOLTAGE;
                break;
            case PLUG:
                timeout = ONLINE_TIMEOUT_PLUG;
                break;
            case REMOTE:
                timeout = ONLINE_TIMEOUT_REMOTE;
                break;
            case PLUGS:
                timeout = ONLINE_TIMEOUT_PLUGS;
                break;
            case GATEWAY:
            	timeout = ONLINE_TIMEOUT_GATEWAY;
            	break;
            case NEW:
                break;
            case ROOT:
                break;
        }
        /**
         * when last_active is after currentTime or currentTime - last_active <= timeout, the device is online
         */
        if (last_active >= currentTime || currentTime - last_active <= timeout)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    

    //这里是查找网关设备  查询他的ip
	@Override
	public IEspDevice doCommandNewActiveLocal(String deviceKey) {
		IEspDevice device;
					long start = System.currentTimeMillis();
		//            //该方法就是请求服务器关于设备的信息的
		//            JSONObject jsonObjectResult = EspBaseApiUtil.Post(URL, jsonObject, header, header2);
		            //这里需要把bssid提取出来
		            String bssid = deviceKey.substring(0, 16);
		            IOTAddress iotxiqueaddress =EspBaseApiUtil.discoverDevice(bssid);
		            long consume = System.currentTimeMillis() - start;
		            
		            //这里可以采取阻塞式的方式进行请求网络信息，最后可以得知消耗了多少时间
		            log.error("search gateway consume: " + consume);
		            EspDeviceType deviceType = EspDeviceType.getDevicetypte(deviceKey);
	            	int serial = deviceType.getSerial();
	            	byte[] hexdat = HEX.decodeHexString((deviceKey.substring(0, 16)));
	            	
	            	long  devid = ((long)hexdat[0]<<56) + ((long)hexdat[1]<<48) + ((long)hexdat[2]<<40) +
	            			((long)hexdat[3]<<32) + ((long)hexdat[4]<<24) + ((long)hexdat[5]<<16)
	            			+((long)hexdat[6]<<8) + ((long)hexdat[7]) ;
	            	long zoneid = EspApplication.curzone.getId();
	            	device =
		                    BEspDevice.getInstance().alloc("gate"+(devid&0xffffff), devid, deviceKey, false, bssid,
		                    					0, serial, null, null, -1, zoneid);
	            	device.getDeviceState().clearState();
	            	if (iotxiqueaddress == null)
		            {
		            	/*  Mark the device is offline
		            	 * 
		            	 * */
		            	device.getDeviceState().addStateOffline();
		            }
		            else{
		            	device.getDeviceState().addStateLocal();
		            	device.setInetAddress(iotxiqueaddress.getInetAddress());
		            
		            }
		           
	                // get current UTC time
	                long currentTime = EspBaseApiUtil.getUTCTimeLong();
	                // usually when the device could be activated suc, it won't get Long.MIN_VALUE,
	                // check here just to prevent the exception happened
	                if (currentTime == Long.MIN_VALUE)
	                {
	                    currentTime = System.currentTimeMillis();
	                }

	                
		                
		
		  return device;
	
   }


	/*
	 * //这里测试 通过gateway如果控制设备成功就返回true 否则返回false
	 * */
	@Override
	public boolean doCommandNewChildActiveLocal(String deviceKey,
			EspDeviceGateway gateway) {
		// TODO Auto-generated method stub
		
		//EspBaseApiUtil.submit(task)
		return false;
	}
	
	
    
}
